package gulimall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import gulimall.constant.AuthServerConstant;
import gulimall.constant.CartConstant;
import gulimall.pojo.to.UserInfoTo;
import gulimall.pojo.vo.Cart;
import gulimall.vo.MemberRespVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author HLF
 * @date 2022/8/11 20:55
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();//同一线程共享ThreadLocal中的数据


    /**
     * 目标方法执行之前，判断是否登录，设置user-key
     * 无论是否登录都必必须有user-key
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        Object member = session.getAttribute(AuthServerConstant.LOGIN_USER);
        ObjectMapper mapper = new ObjectMapper();
        MemberRespVO memberRespVO = mapper.convertValue(member, MemberRespVO.class);

        if (member != null) {//已登录
            userInfoTo.setUserId(memberRespVO.getId());
        }

        //获取请求携带的cookie-->>user-key
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(name)) { //如果cookie的名字是user-key
                    userInfoTo.setUserKey(cookie.getValue());//设置user-key的value
                    userInfoTo.setHasTempUser(true);//cookie里有user-key，所以有临时用户，设置为true
                }
            }
        }

        //如果是第一次请求，user-key为空，手动设置一个cookie-->>name为user-key，value为uuid
        //无论是否是临时用户都要给一个user-key
        if (StringUtils.isBlank(userInfoTo.getUserKey())) {
            //if (!userInfoTo.isHasTempUser()) {  //等价于这样判断，如果是第一次请求，没有临时用户
            String userKey = UUID.randomUUID().toString();
            userInfoTo.setUserKey(userKey);
        }

        threadLocal.set(userInfoTo);

        return true;//全部放行
    }


    /**
     * 目标方法执行之后，通知浏览器保存临时用户的cookie
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();

        if (!userInfoTo.isHasTempUser()) {//如果没有临时用户，需要让浏览器保存一个临时用户
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("firstgulimall.com");//设置cookie的作用域
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);//设置cookie的声明周期
            response.addCookie(cookie);//通知浏览器保存cookie
        }
    }
}
